package cc.laop.utils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class HttpUtil {

	private static final Logger logger = Logger.getLogger(HttpUtil.class);

	private static PoolingHttpClientConnectionManager connMgr;
	private static RequestConfig requestConfig;
	private static CloseableHttpClient httpclient;
	private static final int MAX_TIMEOUT = 30000;

	static {
		// 设置连接池
		connMgr = new PoolingHttpClientConnectionManager();
		// 设置连接池大小
		connMgr.setMaxTotal(1000);
		connMgr.setDefaultMaxPerRoute(50);

		RequestConfig.Builder configBuilder = RequestConfig.custom();
		// 设置连接超时
		configBuilder.setConnectTimeout(MAX_TIMEOUT);
		// 设置读取超时
		configBuilder.setSocketTimeout(MAX_TIMEOUT);
		// 设置从连接池获取连接实例的超时
		configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
		// 在提交请求之前 测试连接是否可用
		configBuilder.setStaleConnectionCheckEnabled(true);
		requestConfig = configBuilder.build();
		httpclient = HttpClients.custom().setConnectionManager(connMgr).build();
	}

	/**
	 * Post 请求
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            请求参数
	 * @param headers
	 *            请求头
	 * @return
	 */
	public static String doPost(String url, Map<String, Object> params,
			Map<String, String> headers) {
		HttpPost httpRequest = new HttpPost(url);
		CloseableHttpResponse httpresponse = null;
		String result = null;
		try {
			httpRequest.setConfig(requestConfig);
			List<NameValuePair> pairList = new ArrayList<>();
			if (params != null) {
				// 设置参数
				for (Map.Entry<String, Object> entry : params.entrySet()) {
					if (entry.getValue() != null) {
						NameValuePair pair = new BasicNameValuePair(
								entry.getKey(), entry.getValue().toString());
						pairList.add(pair);
					}
				}
			}
			if (headers != null) {
				// 设置请求头
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					httpRequest.addHeader(entry.getKey(), entry.getValue());
				}
			}
			httpRequest.setEntity(new UrlEncodedFormEntity(pairList,
					Charset.forName("UTF-8")));

			httpresponse = httpclient.execute(httpRequest);
			int code = httpresponse.getStatusLine().getStatusCode();
			if (code / 100 == 2) {
				result = EntityUtils.toString(httpresponse.getEntity(),
						"UTF-8");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			try {
				if (httpresponse != null) {
					httpresponse.close();
				}
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
		return result;
	}

	/**
	 * Post 请求
	 * 
	 * @param url
	 *            请求地址
	 * @param map
	 *            请求参数
	 * @return
	 */
	public static String doPost(String url, Map<String, Object> map) {
		return doPost(url, map, null);
	}

	/**
	 * Post 请求
	 * 
	 * @param url
	 * @param inputStream
	 * @return
	 */
	public static String doPost(String url, InputStream inputStream) {
		return doPost(url, inputStream, null);
	}

	/**
	 * Post 请求
	 * 
	 * @param url
	 *            请求地址
	 * @param inputStream
	 *            流
	 * @param headers
	 *            请求头
	 * @return
	 */
	public static String doPost(String url, InputStream inputStream,
			Map<String, String> headers) {
		HttpPost httpRequest = new HttpPost(url);
		String result = null;
		CloseableHttpResponse httpresponse = null;
		try {
			httpRequest.setConfig(requestConfig);
			httpRequest.setEntity(new InputStreamEntity(inputStream));
			if (headers != null) {
				// 设置请求头
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					httpRequest.addHeader(entry.getKey(), entry.getValue());
				}
			}
			httpresponse = httpclient.execute(httpRequest);
			int code = httpresponse.getStatusLine().getStatusCode();
			if (code / 100 == 2) {
				result = EntityUtils.toString(httpresponse.getEntity(),
						"UTF-8");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			try {
				if (httpresponse != null) {
					httpresponse.close();
				}
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
		return result;
	}

	/**
	 * Get 请求
	 * 
	 * @param url
	 *            请求地址
	 * @param map
	 *            请求参数
	 * @return
	 */
	public static String doGet(String url, Map<String, Object> map) {
		String result = null;
		HttpGet httpRequest = null;
		CloseableHttpResponse httpresponse = null;
		try {
			// 设置参数
			StringBuffer params = new StringBuffer();
			int i = 0;
			if (map != null) {
				for (Map.Entry<String, Object> entry : map.entrySet()) {
					if (entry.getValue() != null) {
						if (i == 0) {
							params.append("?");
						} else {
							params.append("&");
						}
						params.append(entry.getKey()).append("=")
								.append(entry.getValue());
						i++;
					}
				}
			}
			url = url + params.toString();
			httpRequest = new HttpGet(url);
			httpRequest.setConfig(requestConfig);
			httpresponse = httpclient.execute(httpRequest);
			int code = httpresponse.getStatusLine().getStatusCode();
			if (code / 100 == 2) {
				result = EntityUtils.toString(httpresponse.getEntity(),
						"UTF-8");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			try {
				if (httpresponse != null) {
					httpresponse.close();
				}
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
		return result;
	}

	public static void main(String[] args) {
		String url = "http://185.115.33.29:8080/hls/mal-mtv-arabic.m3u8?key=fb2df05b032581b98f2237ba0de66100";
		String result = HttpUtil.doGet(url, new HashMap<String, Object>());
		System.out.println(result);
	}
}
